package com.android.infantschool.ui.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.KeyEvent;

import com.android.infantschool.R;
import com.android.infantschool.bean.AppUpdateBean;
import com.android.infantschool.bean.BaseBean;
import com.android.infantschool.bean.LoginBean;
import com.android.infantschool.model.config.AppConfig;
import com.android.infantschool.model.http.XUtilsManager;
import com.android.infantschool.model.mvp.presenter.AppUpdatePresenter;
import com.android.infantschool.model.mvp.presenter.AppUpdatePresenterImpl;
import com.android.infantschool.model.mvp.presenter.LoginPresenter;
import com.android.infantschool.model.mvp.presenter.LoginPresenterImpl;
import com.android.infantschool.model.mvp.view.AppUpdateView;
import com.android.infantschool.model.mvp.view.LoginView;
import com.android.infantschool.ui.dialog.DialogAppUpdate;
import com.android.infantschool.ui.dialog.DialogVersion;
import com.android.infantschool.util.Constant;
import com.android.infantschool.util.PermissionUtils;
import com.android.infantschool.util.SystemUtil;
import com.android.infantschool.util.ToastUtil;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import cn.jpush.android.helper.Logger;

/**
 * @author Administrator
 * @particulars
 * @time 2019\6\18 0018 10:18
 * @class describe
 */
public class SplashActivity extends BaseActivity implements LoginView {

    private boolean isStart = false;
    private LoginPresenter loginPresenter;
    private DialogAppUpdate appUpdate = null;//app升级弹窗

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e(TAG, AppConfig.getIsWelCome() + "");
        if (!AppConfig.getIsWelCome()) {
            startActivity(new Intent(this, WelcomeGuideActivity.class));
            finish();
            return;
        }
        setContentView(R.layout.activity_splash);
        loginPresenter = new LoginPresenterImpl(this);
        PermissionUtils.checkMorePermissions(this, permission, new PermissionUtils.PermissionCheckCallBack() {
            @Override
            public void onHasPermission() {
                if (!isStart) {
                    isStart = true;
                    checkApp();
                }
            }

            @Override
            public void onUserHasAlreadyTurnedDown(String... permission) {
                ToastUtil.showShortToast(SplashActivity.this, "拒绝权限可能会影响正常使用");
            }

            @Override
            public void onUserHasAlreadyTurnedDownAndDontAsk(String... permission) {
                ToastUtil.showShortToast(SplashActivity.this, "拒绝权限可能会影响正常使用");
            }
        });
    }

    private String installPath = "";

    private void uodateApp(String url) {
        showAppUpdateDialog();
        XUtilsManager.getInstance().getDownLoad(200, Constant.getFileApp(), url, new XUtilsManager.HttpCallBack() {
            @Override
            public void onEndDownload(int what, String end) {
                Logger.e(TAG, "下载结束,准备安装");
            }

            @Override
            public void onStartDownload(int what, String start) {
                Logger.e(TAG, "开始下载:" + start);
            }

            @Override
            public void onSchedule(int what, int schedule, final String size) {
                if (appUpdate != null) {
                    final int progress = schedule;
                    Logger.e(TAG, "当前App下载进度:" + progress);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            appUpdate.setProgress(progress);
                        }
                    });
                }
            }

            @Override
            public void onResponse(int what, String response) {
                Logger.e(TAG, "下载成功:" + response);
                // TODO: 2019/8/15 去安装
                installPath = response;
                installApk(installPath);
            }

            @Override
            public void onFailure(int what, String error) {
                Logger.e(TAG, "下载失败:" + error);
                start();
            }

            @Override
            public void onFinshed() {
            }
        });
    }

    private void installApk(String fileApk) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri apkUri = FileProvider.getUriForFile(this, "com.android.infantschool.fileprovider", new File(fileApk));
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
            //兼容8.0
            /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                boolean hasInstallPermission = this.getPackageManager().canRequestPackageInstalls();
                if (!hasInstallPermission) {
                    ToastUtil.showShortToast(this, "请允许未知来源应用安装");
                    Uri packageURI = Uri.parse("package:" + getPackageName());
                    Intent intent1 = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
                    intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    this.startActivityForResult(intent1, 102);
                    return;
                }
            }*/
        } else {
            intent.setDataAndType(Uri.fromFile(new File(fileApk)), "application/vnd.android.package-archive");
        }
        this.startActivityForResult(intent, 101);
        this.finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 101) {
            if (appUpdate != null) {
                appUpdate.cancel();
                appUpdate.dismiss();
                appUpdate = null;
            }
        }
    }

    /**
     * App更新
     */
    private void showAppUpdateDialog() {
        if (appUpdate != null) {
            appUpdate.cancel();
            appUpdate.dismiss();
            appUpdate = null;
        }
        appUpdate = new DialogAppUpdate(SplashActivity.this);
        //正在下载时，不可关闭dialog
        appUpdate.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                    return true;
                } else {
                    return false;
                }
            }
        });
        appUpdate.show();
    }

    private void checkApp() {
        AppUpdatePresenter updatePresenter = new AppUpdatePresenterImpl(new AppUpdateView() {
            @Override
            public void errorAppUpdate(String error) {
                start();
            }

            @Override
            public void successAppUpdate(BaseBean baseBean) {
                AppUpdateBean updateBean = (AppUpdateBean) baseBean;
                if (updateBean.getCode() == 0) {
                    if (SystemUtil.getVersionCode() < updateBean.getData().getVercode()) {
                        new DialogVersion(SplashActivity.this, updateBean.getData().getUrl(), updateBean.getData().getVerName(), updateBean.getData().getDescribe(), new DialogVersion.UpdateAppLister() {
                            @Override
                            public void onSeccess(String updateUrl) {
                                uodateApp(updateUrl);
                            }

                            @Override
                            public void onDismiss() {
                                start();
                            }
                        }).show();
                    } else {
                        start();
                    }
                } else {
                    start();
                }
            }
        });
        Map<String, String> map = new HashMap<>();
        updatePresenter.getAppUpdate(map);
    }

    private void start() {
        if (AppConfig.getLoginStatus()) {//记住登录状态了
            if (AppConfig.getLoginType() == 0) {//密码登录
                Map<String, String> map = new HashMap<>();
                map.put("username", AppConfig.getLoginUser());
                map.put("password", AppConfig.getLoginPsw());
                map.put("loginType", "0");
                map.put("role", "0");//教师为0，院长为1
                Log.e(TAG, "map:" + map.toString());
                loginPresenter.postLogin(map);
            } else {//验证码登录
                startActivity(LoginActivity.newIntent(SplashActivity.this));
                finish();
            }
        } else {
            startActivity(LoginActivity.newIntent(SplashActivity.this));
            finish();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e(TAG, "onResume...");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.e(TAG, "onPause...");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            if (isPermissions(grantResults)) {
                if (!isStart) {
                    isStart = true;
                    checkApp();
                }
            }
        }
    }

    private boolean isPermissions(int[] grantResults) {
        boolean isPermiss = true;
        for (int index : grantResults) {
            if (index == -1) {
                isPermiss = false;
            }
        }
        return isPermiss;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (loginPresenter != null) {
            loginPresenter.onDestroy();
            loginPresenter = null;
        }
        if (appUpdate != null) {
            appUpdate.dismiss();
            appUpdate = null;
        }
    }

    @Override
    public void errorLogin(String error) {
        ToastUtil.showShortToast(this, "网络异常" + error);
        startActivity(LoginActivity.newIntent(SplashActivity.this));
        finish();
    }

    @Override
    public void successLogin(BaseBean baseBean) {
        LoginBean loginBean = (LoginBean) baseBean;
        if (loginBean.getCode().equals("0")) {
            AppConfig.setRememberPswStatus(true);
            AppConfig.setLoginStatus(true);
            AppConfig.setToken(loginBean.getData().getToken());
            AppConfig.setUserPhoto(loginBean.getData().getImg());
            AppConfig.setSchoolName(loginBean.getData().getKidUser());
            AppConfig.setUserPhone(loginBean.getData().getTel());
            AppConfig.setNickName(loginBean.getData().getUsername());
            startActivity(MainActivity.newIntent(SplashActivity.this));
            finish();
        } else {
            ToastUtil.showShortToast(this, loginBean.getMsg());
            startActivity(LoginActivity.newIntent(SplashActivity.this));
            finish();
        }
    }
}